import requests
import time
import pymysql
import random
import ac
import json
from itertools import  *

# 禁用警告
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import logging
import os.path
# # 第一步
# logger = logging.getLogger()
# logger.setLevel(logging.INFO) # log等级
# logging.basicConfig(level=logging.NOTSET) #设置日志级别
# # 第一步，创建一个logger
# logger = logging.getLogger()
# logger.setLevel(logging.INFO)  # Log等级总开关
# # 第二步，创建一个handler，用于写入日志文件
# rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
# log_path = os.path.dirname(__file__) + '/Logs/'
# log_name = log_path + rq + '.log'
# logfile = log_name
# fh = logging.FileHandler(logfile, mode='w')
# fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
# # 第三步，定义handler的输出格式
# formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
# fh.setFormatter(formatter)
# # 第四步，将logger添加到handler里面
# logger.addHandler(fh)
# 发送列表
send_list = []
# 连接sql
def send_id():
    coon = pymysql.connect('127.0.0.1','root','123456','bili',charset = 'utf8')
    # 建立游标
    cursor = coon.cursor()
    # sql语句
    sql = 'SELECT userid,username from bili_user_info where play_sum > 10000 and follower > 1000 and sex != "男" LIMIT 459,10'
    cursor.execute(sql)
    userids = cursor.fetchall()
    for user in userids:
        send_list.append(user)
send_id()

ac_list = ac.pwd_list.get('ac_list')


for nums,send in enumerate(send_list):
    pages = (nums+1) % 1
    ac = ac_list[pages]
    sid = send[0]
    sname = send[1]
    cookie = ac.get('cookie')
    sender_uid = ac.get('sender_uid')
    dev_id = ac.get('dev_id')
    csrf_token = ac.get('csrf_token')
    content = ac.get('content')
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Cookie": cookie,
        "Host": "api.vc.bilibili.com",
        "Origin": "https://message.bilibili.com",
        "Referer": "https://message.bilibili.com/?spm_id_from=333.788.v_upinfo.3",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
    }
    formData = {
    'msg[sender_uid]': sender_uid, # 自己的id
    'msg[receiver_id]': sid, # 要发送的id
    'msg[receiver_type]': 1,
    'msg[msg_type]': 1,
    'msg[content]': '{"content":"'+str(content)+'"}', # 内容
    'msg[timestamp]': str(int(time.time())),
    'msg[dev_id]': dev_id,
    'csrf_token': csrf_token,
    }
    base_url = 'https://api.vc.bilibili.com/web_im/v1/web_im/send_msg'
    time.sleep(20)
    today_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    print('ID为: {userid},昵称为 {username} {timess}发送完成!'.format(userid = sid,username = sname,timess = today_time))

    print('发送账户为:%s' % sender_uid)
    html_res = requests.post(base_url,data=formData,headers = headers, verify = False)
    print(html_res.text)
    print('------消息发送完成------')









